from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QWidget
import sys
from PySide2.QtCharts import QtCharts
from PySide2.QtWidgets import QHBoxLayout
from PySide2.QtGui import QColor, QPen
from PySide2.QtCore import Qt
import openpyxl

class MyChartWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(500, 300)
        # 图 - View - Series
        self.chart = QtCharts.QChart()
        self.view = QtCharts.QChartView(self.chart)
        self.personNumber = QtCharts.QSplineSeries()
        self.personNumber_Y = QtCharts.QValueAxis()
        layout = QHBoxLayout()
        layout.addWidget(self.view)
        self.setLayout(layout)
        self.wb = openpyxl.load_workbook(
            'C:\\Users\\zuozh\\Desktop\\太原科大Python综合培训\\国家数据\\人口\\总人口.xlsx'
        )
        self.ws = self.wb['年度数据']
        self.__initChart()

    def __initChart(self):
        self.personNumber_Y.setTitleText('总人口（万人）')
        self.personNumber_Y.setRange(125000, 140000)
        self.personNumber_Y.setLabelFormat('%u')
        self.personNumber_Y.setLabelsVisible(True)
        self.personNumber_Y.setTickCount(10)
        self.personNumber_Y.setMinorTickCount(10)

        self.chart.addAxis(self.personNumber_Y,
                            Qt.AlignLeft)


        self.personNumber.setPen(
            QPen(QColor("red"))
        )
        self.personNumber.setName('总人口')

        for i in range(2, 22):
            self.personNumber.append(
                int(self.ws.cell(row=3, column=i).value[:4]),
                int(self.ws.cell(row=4, column=i).value)
            )

        self.chart.setAxisY(
            self.personNumber_Y,
            self.personNumber
        )

        self.chart.setTitle('人口趋势变化图')
        self.chart.setAnimationOptions(
            QtCharts.QChart.AllAnimations
        )
        self.chart.addSeries(self.personNumber)

if __name__ == "__main__":
    app = QApplication()

    mcw = MyChartWidget()
    mcw.show()

    sys.exit(app.exec_())